<template>
  <div class="pad-out-box">
    <div class="box-card margin-bottom-20 padding-bottom-20" v-for="(item, index) in list" :key="item.primaryKey">
      <div class="flex align-center justify-between">
        <span class="font-size-16 font-weight-700 padding-bottom-15">{{ item.chargeItemAliasName }}</span>
        <div>
          <el-button class="f-right margin-left-20" type="text" @click="save(index)">保存</el-button>
          <el-button class="f-right" type="text" @click="configMatter(index)">配置事项</el-button>
        </div>
      </div>
      <div>
        <form-common v-if="filedList[index]" :filed-list="filedList[index]" :ref="`form${index}`" @selectChange="selectChange"></form-common>
        <el-tag v-for="(matter, matterIndex) in item.taxRuleList" :key="matterIndex" :type="matter.calculateMethod == 1 ? 'success' : 'danger'" closable @close="removeMatter(item.taxRuleList, matterIndex)" class="margin-right-20 margin-right-15">
          <span>{{ getMatterTxt(matter.calculateItemKey) }}</span>
          <span class="padding-left-5" v-if="matter.calculateMethod == 0">-</span>
          <span class="padding-left-5" v-if="matter.calculateMethod == 1">+</span>
        </el-tag>
      </div>
    </div>

    <!-- 配置事项 -->
    <el-dialog title="配置事项" :visible.sync="dialog" width="45%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="matterFiledList" ref="matter"></form-common>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="saveMatter">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import formCommon from '@g/components/form/formCommon.vue';
    import { taxFiledList, matterFiledList } from './form.js';
    import { apiConstant } from '@/api';
    import { apiTaxAdd, apiTaxUpdate, apiTaxList, apiMatterList } from '../../api/tax';
    import { requestTips, askDialog } from '../../assets/util';
    import { guid } from '@/common/js/utils';

    export default {
      data() {
        return {
          filedList: [],
          dialog: false,
          matterFiledList: matterFiledList,
          currentIndex: 0,
          list: [],
          matterList: [],
        };
      },

      mounted() {
        this.getMatter();
        this.getConstant();
      },

      methods: {
        //常量
        async getConstant() {
          let res = await apiConstant({});
          taxFiledList.forEach(item => {
            if (item.bindFieldName == 'taxType') {
              item.optionList = res.taxItemType || [];
            }
          });
          this.getList();
        },

        //事项类型
        async getMatter() {
          let enterpriseid = localStorage.getItem('userEnterpriseid')
          let res = await apiMatterList({
            bizId:this.$route.query.enterpriseid ? this.$route.query.enterpriseid : enterpriseid,
            queryLastLevel:true,
            matterType:1
          });
          matterFiledList.forEach(item => {
            if (item.bindFieldName == 'calculateItemKey') {
              item.optionList = res.rows || [];
            }
          });
          this.matterList = res.rows || [];
        },

        //数据源
        async getList() {
          this.filedList = [];
          let res = await apiTaxList({ projectKey: this.$route.query.projectKey });
          this.list = res.rows || [];
          this.list.forEach(item => {
            let _taxFiledList = JSON.parse(JSON.stringify(taxFiledList));
            let isRequired = item.taxType == 2 ? true : false;
            this.initFormRequired(_taxFiledList, 'deductRate', isRequired);
            this.setFiledVal(_taxFiledList, item);
            this.filedList.push(_taxFiledList);
          });
        },

        //保存税项
        async save(index) {
          let formName = 'form' + index;
          let model = this.$refs[formName][0].validateForm();
          if (!model) return;
          if (model.taxType == 1) {
            if (this.list[index].taxRuleList.length == 0) {
              this.$message.warning('请配置事项!');
              return;
            }
          }
          model.taxRuleList = this.list[index].taxRuleList;
          this.list[index].projectKey = this.$route.query.projectKey;
          for (let i in this.list[index]) {
            for (let j in model) {
              if (i == j) {
                this.list[index][i] = model[j];
              }
            }
          }
          let res = this.list[index].bizType == 'project' ? await apiTaxUpdate(this.list[index]) : await apiTaxAdd(this.list[index]);
          requestTips(res, () => {
            this.getList();
          });
        },

        //保存事项
        saveMatter() {
          let model = this.$refs.matter.validateForm();
          if (!model) return;
          this.list[this.currentIndex].taxRuleList.push({
            calculateItemKey: model.calculateItemKey,
            calculateMethod: model.calculateMethod,
          });
          this.dialog = false;
        },

        //配置事项
        configMatter(index) {
          this.currentIndex = index;
          this.dialog = true;
          this.$nextTick(() => {
            this.$refs.matter.initModel();
          });
        },

        //删除事项
        removeMatter(list, index) {
          list.splice(index, 1);
        },

        //form的事件
        selectChange(data) {
          if (data.filedName == 'taxType') {
            if (data.filedVal == 2) {
              data.setValidateFn(['deductRate'], true);
            } else {
              data.setValidateFn(['deductRate'], false);
            }
          }
        },

        //取事项的txt
        getMatterTxt(key) {
          let targetObj = this.matterList.find(item => item.chargeItemKey == key);
          return targetObj.chargeItemAliasName || '';
        },

        //初始化filed必填
        initFormRequired(list,filedName, type) {
          list.forEach(item => {
            if (item.bindFieldName == filedName) {
              item.isRequired = type;
            }
          });
        },

        //formCommon字段回显
        setFiledVal(list, row) {
          list.forEach(item => {
            for (let i in row) {
              if (i == item.bindFieldName) {
                item.bindFieldVal = row[i];
              }
            }
          });
        },
      },

      components: { formCommon },
    };
</script>
<style scoped lang="scss">
  .box-card {
    border-bottom: 5px solid #f1f1f1;
  }
  ::v-deep .el-form .el-form-item__label {
    padding-left: 0;
  }
</style>
